package top.zhangjianyong.tools.config.json;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

/**
 * @author ： zhangjianyong
 * @date ： 2022/8/4 3:57 PM
 */
public class LocalDateTimeToStringSerializer implements ObjectSerializer {

    private DateTimeFormatter DTF;

    public LocalDateTimeToStringSerializer(String format) {
        this.DTF = DateTimeFormatter.ofPattern(format);
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;
        if (object instanceof TemporalAccessor){
            TemporalAccessor date = (TemporalAccessor) object;
            out.writeString(DTF.format(date));
        } else {
            out.writeNull();
        }
    }
}
